const db = require('../dbbase/db');
const { jwtSecret } = require('../config/default');
const jwt = require('jsonwebtoken');
const uid = require("node-uuid");


//新用户注册
exports.userRegister = (req, res, next) => {
    try {
        //1.获取请求数据
        const userData = req.body.user;
        const userid = uid.v1();
        //2.数据验证
        
        //3.将数据保存到数据库中
        const sql = "INSERT INTO mov_app_users(id,USERNAME, USERCODE, PASSWORD) VALUES(:1, :2, :3, :4)";
        const params = [userid,userData.username,userData.usercode,userData.password];
        db.query(sql, params).then((result) => {
            res.status(200).json(result)
        }).catch((err) => {
            console.log(err);
        });
    } catch (err) {
        next(err)
    }
}

//用户登录
exports.userLogin = async (req, res, next) => {
    console.log();
    try {
        //1、数据验证。

        //2、生成token.
        const user = req.body.user;
        const token = await jwt.sign({
            usercode: user.usercode
        }, jwtSecret, { expiresIn: 60 * 60 * 24 })
        console.log(token);
        //3、发送包含token的成功相应。
        res.status(200).json({
            ...user,
            token
        })
    } catch (err) {
        console.log(err);
        next(err)
    }
}



//获取当前用户信息
exports.getUser = (req, res, next) => {
    //1.获取token
    let token = req.headers["authorization"];
    token = token ? token.split('token ')[1] : null;
    if (!token) {
        return res.status(403).end()
    }
    //2.验证token
    const decoderToken = verify(token, jwtSecret);
    User.findById(decoderToken.userId).then((user) => {
        if (user) {
            res.status(402).json(user)
        } else {
            return res.status(402).end()
        }
    }).catch((err) => {
        res.status(403).end()
    })
}
